﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：SqlServerSettingStore.cs
// 功能描述：TongTongMall.MallWeb.DapperFramework
// 
// Create User：jym 2017/02/09
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Configuration;
using TongTongMall.Dependecy;
using TongTongMall.Domain.Repositories.Repositories;
using TongTongMall.MallWeb.Core.Tenant;

namespace TongTongMall.DapperFramework.Configuration.Setting
{
    public class SqlServerSettingStore : ISettingStore, ISingletonDependency
    {
        public IRepository<TenantSysConfig, long> _tenantSysConfigRepository { get; set; } = IocManager.Instance.IocContainer.Resolve<IRepository<TenantSysConfig, long>>();

        public async Task CreateAsync(SettingInfo setting)
        {
            await _tenantSysConfigRepository.InsertAsync(new TenantSysConfig
            {
                //Id = Guid.NewGuid(),
                Name = setting.Name,
                TenantID = setting.TenantID,
                UserID = setting.UserID,
                Value = setting.Value
            });
        }

        public async Task DeleteAsync(SettingInfo setting)
        {
            await _tenantSysConfigRepository.DeleteAsync(new { TenantID = setting.TenantID, UserID = setting.UserID, Key = setting.Name });
        }

        public async Task<List<SettingInfo>> GetAllListAsync(long? tenantId, long? userId)
        {
            var list = await _tenantSysConfigRepository.GetAllListAsync(new { TenantID = tenantId, UserID = userId });
            if (list.Count > 0)
            {
                return list.Select(x => new SettingInfo { Name = x.Name, TenantID = x.TenantID, UserID = x.UserID, Value = x.Value }).ToList();
            }
            return new List<SettingInfo>();
        }

        public async Task<SettingInfo> GetSettingOrNullAsync(long? tenantId, long? userId, string key)
        {
            var detail = await _tenantSysConfigRepository.FirstOrDefaultAsync(new { TenantID = tenantId, UserID = userId, Key = key });
            if (detail != null)
            {
                return new SettingInfo { Name = detail.Name, TenantID = detail.TenantID, UserID = detail.UserID, Value = detail.Value };
            }
            return default(SettingInfo);
        }

        public async Task UpdateAsync(SettingInfo setting)
        {
            await _tenantSysConfigRepository.UpdateAsync(new { Value = setting.Value }, new { TenantID = setting.TenantID, UserID = setting.UserID, Key = setting.Name });
        }
    }
}
